package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Visitor;
import com.tanhua.dubbo.api.VisitorApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Classname VisitorApiImpl
 * @Description TODO 访客实现类
 * @Date 2021/3/17 19:34
 * @Created by gan
 */
@Service
public class VisitorApiImpl implements VisitorApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据上次访问时间与当前用户id 查询前5条访客列表记录
    @Override
    public List<Visitor> queryVisitors(String time, Long userId) {
        //创建查询条件
        Query query =new Query();
        query.addCriteria(Criteria.where("userId").is(userId)
        .and("date").is(time));
        query.limit(5);

        return mongoTemplate.find(query,Visitor.class);
    }



    //根据当前用户id 查询前5条访客列表记
    @Override
    public List<Visitor> queryVisitors(Long userId) {
        //构造查询条件
        Query query= new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        //进行排序
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(5);
        return mongoTemplate.find(query,Visitor.class);
    }


    //保存访客信息
    @Override
    public void save(Visitor visitor) {
        //构造访客信息，返回

        visitor.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitor);
    }
}
